<?php
/**
 * +----------------------------------------------------------------------
 * | Copyright © Sogu Technologies Co. Ltd 2018-2050 All rights reserved.
 * +----------------------------------------------------------------------
 * | File name: LoanRequest.php
 * +----------------------------------------------------------------------
 * | Author: sam
 * +----------------------------------------------------------------------
 * | Description: 用于详细说明此程序文件完成的主要功能，与其他模块或函数的接口、输出值、取值范围、含义及参数间的控制、顺序或依赖等关系。
 * +----------------------------------------------------------------------
 * | Others: 其他内容的说明
 * +----------------------------------------------------------------------
 * | History: 修改历史记录列表，每条修改记录应包含修改日期、修改者及修改内容简述
 * +----------------------------------------------------------------------
 * | 1.Date: 2019-02-28 Author: sam Modification: 创建
 * +----------------------------------------------------------------------
 */

namespace App\ModelTransfers\Traits;


use App\Models\User;
use App\Models\UserBankCard;
use App\Models\UserGlobal;
use App\Models\UserLoanRequest;
use App\ModelTransfers\TransferInterface\TransferInterface;
use App\ModelTransfers\WsFund\WsFund;
use App\ModelTransfers\WsLoans\LoanApply;
use App\ModelTransfers\WsXinLiu\WsXinLiu;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

Trait LoanRequest
{
    protected static $channel = [
        'LCC201709190009'=>'10009',
        'LCC201709190010'=>'JCFC',
    ];

    protected static $purpose = [
        'consume'=>'08',
        'education'=>'02',
        'decorate'=>'04',
        'tourism'=>'01',
        'marry'=>'03',
        'appliance'=>'05',
        'car'=>'06',
        'dailyGoods'=>'07'
    ];


    /**
     * Description:
     * Author: Sam
     * DateTime: 2019-02-28 17:58
     * @param $ws_user_id
     * @return array
     * @throws \Exception
     */
    public static function moveLoanApply($ws_user_id){
        die('废弃了');
        $user = User::where('old_kskd_user_id',$ws_user_id)->first();
        $query_begin = microtime(true);
        $loans = LoanApply::with([
            'wsFund'=>function($q){$q->select(['status','credit_time','loan_term','loan_amount','channel_credit_id','update_time','fail_reason','apply_id']);},
            'wsXinLiu'=>function($q1){$q1->select(['status','create_time','loan_term','loan_amount','finish_time','apply_id']);},
            'cash_card'=>function($q2){$q2->select(['id','card_no']);},
            'credit_card'=>function($q3){$q3->select(['id','card_no']);}])
            ->select(['loan_purpose','apply_amount','apply_term','apply_time','loan_channel','bank_card_id','credit_card_id','id'])
            ->where('user_id',$ws_user_id)->get();
        Log::debug('query cost  :'.(microtime(true)-$query_begin).' s');
        $return  = [];
        $insert_begin = microtime(true);
        try{
            foreach ($loans as $key => $loan){
                $loan_data = [];
                if($loan->cash_card){
                    $cash_id = UserBankCard::where('card_num',$loan->cash_card->card_no)->value('id');
                }
                if($loan->credit_card){
                    $credit_id = UserBankCard::where('card_num',$loan->credit_card->card_no)->value('id');
                }
                $purpose = $loan->loan_purpose;
                if(!empty($purpose)){
                    $loan_data['use'] = self::$purpose[$purpose];
                }
                $loan_data['cash_card_choice_id'] = $cash_id??0;
                $loan_data['credit_card_choice_id'] = $credit_id??0;
                $loan_data['user_id'] = $user->id;
                $loan_data['is_valid'] = $loan->is_valid;
                $loan_data['loan_money'] = $loan->apply_amount;
                $loan_data['period'] = $loan->apply_term;
                $loan_data['apply_time'] = $loan->apply_time;
                $loan_data['trans_id'] = $loan->id;
                $loan_data['data_sign'] = 1;
                $channel = $loan->loan_channel;
                $loan_data['channel'] = in_array($loan->loan_channel,['LCC201709190009','LCC201709190010'])?self::$channel[$channel]:'long_xin';
                if(!empty($loan->wsFund)){ //晋商
                    /**
                     * 判断授信成功失败
                     */
                    if(in_array($loan->wsFund->status,[120,121,122,123])){
                        $loan_data['status'] = 3;
                    }elseif($loan->wsFund->status == 130){
                        $loan_data['status'] = 4;
                    }elseif($loan->wsFund->status == 110){
                        $loan_data['status'] = 2;
                    }else{
                        $loan_data['status'] = 0;
                    }

                    if($loan_data['status']==3){ //授信成功
                        $loan_data['credit_time'] = $loan->wsFund->credit_time;
                        $loan_data['actually_period'] = $loan->wsFund->loan_term;
                        $loan_data['actually_loan_money'] = $loan->wsFund->loan_amount*100;
                        $loan_data['credit_id'] = $loan->wsFund->channel_credit_id;
                        $loan_data['risk_status'] = 1;
                    }elseif($loan_data['status']==4){ //授信失败
                        $loan_data['failed_time'] = $loan->wsFund->update_time;
                        $loan_data['failed_reason'] = $loan->wsFund->fail_reason;
                        $loan_data['risk_status'] = 2;
                    }
                }elseif(!empty($loan->wsXinLiu)){ //光大
                    /**
                     * 判断授信成功失败
                     */
                    if($loan->g_status == 2){
                        $loan_data['status'] = 3;
                    }elseif($loan->g_status == -1){
                        $loan_data['status'] = 4;
                    }elseif($loan->g_status == 1){
                        $loan_data['status'] = 2;
                    }
                    if($loan_data['status']==3){ //授信成功
                        $loan_data['credit_time'] = $loan->wsXinLiu->create_time;
                        $loan_data['actually_period'] = $loan->wsXinLiu->loan_term;
                        $loan_data['actually_loan_money'] = $loan->wsXinLiu->apply_amount*100;
                        $loan_data['risk_status'] = 1;
                    }elseif($loan_data['status']==4){ //授信失败
                        $loan_data['failed_time'] = $loan->wsXinLiu->finish_time;
                        $loan_data['risk_status'] = 2;
                    }
                }
                $id = UserLoanRequest::create($loan_data)->id;
                if(in_array($loan->loan_channel,['LCC201709190009','LCC201709190010'])){
                    if(!empty($loan_data['status'])&&$loan_data['status']==3){
                        $return[$loan_data['trans_id']] = $id;
                    }
                }else{
                    $return[$loan_data['trans_id']] = $id;
                }
            }
            Log::debug('insert cost :'.(microtime(true)-$insert_begin).' s');
            return $return;
        }catch(\Exception $e){
            Log::debug('迁移授信数据失败'. $e->getMessage().$e->getLine());
            throw new \Exception("文件：{$e->getFile()}&&行数：{$e->getLine()}&&错误信息：{$e->getMessage()} \n",$e->getCode());
        }
    }

    public static function moveLoanRequestByDB($old_user_id)
    {
        $user = User::where('old_kskd_user_id',$old_user_id)->first();
        $loans = DB::connection('transfer')->table('ws_loan.loan_apply as l')
//            ->leftJoin('ws_fund.uni_fund_order as j','l.id','=','j.apply_id')
            ->leftjoin('ws_fund.uni_fund_order as j', function ($join) {
                $join->on('l.id', '=', 'j.apply_id')
                ->whereIn('j.status',[120,121,122,123]);
            })
//            ->leftJoin('ws_xinliu.credit_order as g','l.id','=','g.apply_id')
            ->leftjoin('ws_xinliu.credit_order as g', function ($join) {
                $join->on('l.id', '=', 'g.apply_id')
                    ->where('g.status',2);
            })
            ->leftJoin('ws_account.pay_bind_card as cash','l.bank_card_id','=','cash.id')
            ->leftJoin('ws_account.pay_bind_card as credit','l.credit_card_id','=','credit.id')
            ->leftJoin('ws_fund.st_report_bankandrisk as s','l.id','=','s.apply_id')
            ->select([
                'l.is_valid',
                'l.loan_purpose',
                'l.apply_amount',
                'l.apply_term',
                'l.apply_time',
                'l.loan_channel',
                'l.id',
                'j.status as j_status',
                'j.credit_time as j_credit_time',
                'j.loan_term as j_loan_term',
                'j.loan_amount as j_loan_amount',
                'j.channel_credit_id as j_channel_credit_id',
//                'j.update_time as j_failed_time',
//                'j.fail_reason as j_fail_reason',
                'g.status as g_status',
                'g.create_time as g_credit_time',
                'g.loan_term as g_loan_term',
                'g.loan_amount as g_loan_amount',
//                'g.finish_time as g_failed_time',
                's.bank_code',
                'cash.id as cash_id',
                'credit.id as credit_id'
            ])->where('l.user_id',$old_user_id)
            ->where('l.apply_status','>',2)
            ->get();
        $return  = [];
        if($loans->count()>0){
            try{
                foreach ($loans as $key => $loan){
//                    if(UserLoanRequest::where('trans_id',$loan->id)->first()){
//                        continue;
//                    }
                    $loan_data = [];
                    $cash_id = UserBankCard::where('card_num',$loan->cash_id)->value('id');
                    $credit_id = UserBankCard::where('card_num',$loan->credit_id)->value('id');
                    $purpose = $loan->loan_purpose;
                    if(!empty($purpose)){
                        $loan_data['use'] = self::$purpose[$purpose];
                    }
                    $loan_data['cash_card_choice_id'] = $cash_id??0;
                    $loan_data['credit_card_choice_id'] = $credit_id??0;
                    $loan_data['user_id'] = $user->id;
                    $loan_data['is_valid'] = $loan->is_valid;
                    $loan_data['loan_money'] = $loan->apply_amount??0;
                    $loan_data['period'] = $loan->apply_term??0;
                    $loan_data['apply_time'] = $loan->apply_time??0;
                    $loan_data['trans_id'] = $loan->id;
                    $loan_data['data_sign'] = 1;
                    $channel = $loan->loan_channel;
                    if(in_array($loan->loan_channel,['LCC201709190009','LCC201709190010'])){
                        $loan_data['channel'] = empty($loan->bank_code)?self::$channel[$channel]:$loan->bank_code;
                    }else{
                        $loan_data['channel'] = 'long_xin';
                    }
                    $loan_data['channel'] = in_array($loan->loan_channel,['LCC201709190009','LCC201709190010'])?self::$channel[$channel]:'long_xin';
                    $loan_data['status'] = 3;
                    if(!empty($loan->j_status)){
                        /**
                         * 判断成功失败
                         */
//                        if(in_array($loan->j_status,[120,121,122,123])){
//                            $loan_data['status'] = 3;
//                        }elseif($loan->j_status == 130){
//                            $loan_data['status'] = 4;
//                        }elseif($loan->j_status == 110){
//                            $loan_data['status'] = 2;
//                        }else{
//                            $loan_data['status'] = 0;
//                        }
//                        if($loan_data['status']==3){ //授信成功
                            $loan_data['credit_time'] = $loan->j_credit_time;
                            $loan_data['actually_period'] = $loan->j_loan_term;
                            $loan_data['actually_loan_money'] = $loan->j_loan_amount*100;
                            $loan_data['credit_id'] = $loan->j_channel_credit_id;
                            $loan_data['risk_status'] = 1;
//                        }elseif($loan_data['status']==4){ //授信失败
//                            $loan_data['failed_time'] = $loan->j_failed_time;
//                            $loan_data['risk_status'] = 2;
//                        }
                    }elseif(!empty($loan->g_status)){
//                        if($loan->g_status == 2){
//                            $loan_data['status'] = 3;
//                        }elseif($loan->g_status == -1){
//                            $loan_data['status'] = 4;
//                        }elseif($loan->g_status == 1){
//                            $loan_data['status'] = 2;
//                        }else{
//                            $loan_data['status'] = 0;
//                        }
//                        if($loan_data['status']==3){ //授信成功
                            $loan_data['credit_time'] = $loan->g_credit_time;
                            $loan_data['actually_period'] = $loan->g_loan_term;
                            $loan_data['actually_loan_money'] = $loan->g_loan_amount*100;
                            $loan_data['risk_status'] = 1;
//                        }elseif($loan_data['status']==4){ //授信失败
//                            $loan_data['failed_time'] = $loan->g_failed_time;
//                            $loan_data['risk_status'] = 2;
//                        }
                    }else{
//                        $loan_data['status'] = 3;
                        $loan_data['actually_period'] = $loan->apply_term??0;
                        $loan_data['actually_loan_money'] = $loan->apply_amount??0;
                    }
                    $id = UserLoanRequest::create($loan_data)->id;
                    $return[$loan_data['trans_id']] = $id;
//                    if(in_array($loan->loan_channel,['LCC201709190009','LCC201709190010'])){
//                        if(!empty($loan_data['status'])&&$loan_data['status']==3){
//                            $return[$loan_data['trans_id']] = $id;
//                        }
//                    }else{
//                        $return[$loan_data['trans_id']] = $id;
//                    }
                }
//                UserGlobal::where('uid',$user->id)->update(['global_status'=>UserGlobal::STATUS_LOAN_REQUEST_SUCCESS]);
                return $return;

            }catch (\Exception $e){
                Log::debug('授信处理失败'.$e->getMessage()||$e->getFile());
                throw new \Exception("文件：{$e->getFile()}&&行数：{$e->getLine()}&&错误信息：{$e->getMessage()} \n",$e->getCode());
            }
        }


    }

    public static function test(){
//        dd(WsXinLiu::first());
//        dd(WsFund::first());
        $res = LoanApply::with(['wsFund','wsXinLiu','cash_card','credit_card'])->where('user_id','US201708090000040059')->get();
        foreach ($res as  $k => $v){
            dd($v->wsFund);
        }
    }

    /**
     * Description:删除迁移用户授信记录
     * Author: Sam
     * DateTime: 2019-03-13 11:15
     * @param null $user_id
     * @throws \Exception
     */
    public static function RollBack($user_id = null){
        $query = UserLoanRequest::query();
        if($user_id){
            $query->where('user_id',$user_id);
        }
        $query->where('data_sign',1)->delete();
    }
}